package com.zzy.demo.common.util.rsa;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

public class TestRsa {

    // 私钥对象
    private PrivateKey sk;
    // 公钥对象
    private PublicKey pk;

    // 私钥字符串
    private static String privateKeyStr ="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIK2l62kOOFJQJaKonU2nyG3lrIHSfcp4Yu1wLgQsGYiKBxKM+1Xp93KSTIM2c359491nP20HvmPD8MGOJHSu/4HWEW+h8R2SKS+JO+9UBb+ZKGyojf28Fnb4L2VkpvXuFazKk5iCeGSid2SRKwqLZXPS8YZpxIT2gMnP5dyhzXPAgMBAAECgYBHA5ZSIxc35gkuAHGUhrFbqxc271jS7DD6KythlMeRJVtvSyz89BNiHqU3iN3H1tcVXIuHFhWB9aRViwquxrOU1OIxagkkCXGd+qZuaeENjqvBbr/uooCf2ZaQdFxb44VG5cXk5uTcBC5ZNQWNeEhaXxD6r+aCBA4My7UUiLTHmQJBAP0zUcbbTvW1sDKAZR+fTkw+fC9kxqDHHLpdSd+/SB3pv/83klF5c4Bwo9PSF59YZFG04SiLDXEhFGgWneUbRa0CQQCEKJMaJU7aDlyEpq8CcNGOU4AU20KvSVbxBWk0ybKmKad76SrFSzSM5rECTvx3wHW4fp2NnOC/DO85FshJv0DrAkAp4E37HJRfkPAWOiP/aeKSO5dgY0NyndvDeuBX8BPmVp2ZgUBi1zpiGL8PrmSXxw+4b7j5cp4DgtwUJwFwPeV1AkASMoQO1ZRF8jRLD6iJbX9tWZIJTSeheze9eEFEQ4GV36ZwKWr6P6C8xgcZika5Nob/IHART8iiheVqtvhdLziBAkARTH7aaEEOyynDFObpcj+z2Z7jmxUd/d0eOd/kIMJCYoK7zrosf/Wrt3/c+tvxFL/K3AJUXvYTtworqKCEnofF";
    // 公钥字符串
    private static String publicKeyStr ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCtpetpDjhSUCWiqJ1Np8ht5ayB0n3KeGLtcC4ELBmIigcSjPtV6fdykkyDNnN+fePdZz9tB75jw/DBjiR0rv+B1hFvofEdkikviTvvVAW/mShsqI39vBZ2+C9lZKb17hWsypOYgnhkondkkSsKi2Vz0vGGacSE9oDJz+Xcoc1zwIDAQAB";
    
	public static final String RSA_ALGORITHM_NOPADDING = "RSA";

    // 初始化公钥私钥
    public TestRsa() throws NoSuchAlgorithmException {
        KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA");
        rsa.initialize(1024);
        KeyPair keyPair = rsa.generateKeyPair();
        sk = keyPair.getPrivate();
        pk = keyPair.getPublic();

        privateKeyStr = new String(Base64.encodeBase64(sk.getEncoded()));
        publicKeyStr = new String(Base64.encodeBase64(pk.getEncoded()));
    }

    // 公钥加密
    public static String encrypt(String str, String publicKey) throws Exception {
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

    // 私钥解密
    public static String decrypt(String data, String privateKeyStr) throws Exception {
		KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM_NOPADDING);
		byte[] privateKeyArray = privateKeyStr.getBytes();
		byte[] dataArray = data.getBytes("UTF-8");
		PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyArray));
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
		
		Cipher cipher = Cipher.getInstance(RSA_ALGORITHM_NOPADDING);
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		return new String(cipher.doFinal(Base64.decodeBase64(dataArray)), "UTF-8");
    }

    // 私钥签名
    public String sign(String str) throws Exception {
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(this.sk);
        signature.update(str.getBytes());
        byte[] sign = signature.sign();
        return new String(Base64.encodeBase64(sign));
    }

    // 公钥验证
    public boolean verify(String str, String sign) throws Exception {
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initVerify(this.pk);
        signature.update(str.getBytes());
        return signature.verify(Base64.decodeBase64(sign.getBytes("UTF-8")));
    }


    public static void main(String[] args) throws Exception {

        System.out.println("publicKeyStr:"+ TestRsa.publicKeyStr);
        System.out.println("privateKeyStr:"+ TestRsa.privateKeyStr);
        String encodeStr = "UgFgo5R8jy0bq3IK5jlIeAoiccFoflweIv9x2/bA7x9BRNJH1Yftw65xb0pXAJoUDPEBk1opF6JS1TXsj1dazrkf34wcOu4ahYYbKE5V37R0m4jn7VXsq/LwWtUd06OcnKh9Tf2pTifv9qLo9gXZYR2Vhb/03ao30PubyTyV9L0=";
        
        System.out.println("encodeStr:"+encodeStr);
        
        String backEncode = TestRsa.encrypt("woshi中国@.com", TestRsa.publicKeyStr);
        System.out.println("backEncode:"+backEncode);
        
        String result = TestRsa.decrypt(encodeStr ,TestRsa.privateKeyStr);
        System.out.println("result:"+result);

    }
}
